package com.liver_cloud.service.common;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.stereotype.Service;

import com.liver_cloud.dao.mybatis.DaoSupport;
import com.liver_cloud.util.ImageUpLoader;
import com.liver_cloud.util.PageData;

@Service
public class CommonService {
	
	@Resource(name = "daoSupport")
	private DaoSupport dao;
	
	
	public List<PageData> getPushMessageList(PageData pd) throws Exception {
		
		String userType = pd.getString("userType"); 
					
		//如果是1，则是医生查询，2：助手查询，3：患者查询
		if("1".equals(userType)){			
			
			return getDoctorMessageList(pd);
		
		}else if("2".equals(userType)){
			
			return getAssistantMessageList(pd);
			
		}else{
			
			return getPatientMessageList(pd);
		}
	}
	
	
	private List<PageData> getPatientMessageList(PageData pd) throws Exception {
		
		List<PageData> pushMessageList = 
				(List<PageData>) dao.findForList("AssistantMapper.getPushMessageList", pd);	
		
		if(pushMessageList.size()==0){
			return pushMessageList;
		}
		//遍历集合，预处理数据
		for(int i=0;i<pushMessageList.size();i++){
			String idTemp = pushMessageList.get(i).get("userId").toString();
			String messageType =  pushMessageList.get(i).get("messageType").toString();	
			String pushMessageId = pushMessageList.get(i).get("pushMessageId").toString();
			//添加是否是新消息
			List<PageData> reader = (List<PageData>) dao.findForObject("PatientMapper.findReader", pd);
			if(reader.size()==0){
				pushMessageList.get(i).put("ifChanged", true);
			}else{
				pushMessageList.get(i).put("ifChanged", false);
			}
			addInfor(messageType,pushMessageList,pushMessageId,idTemp,i,pd);			
		}		
		return pushMessageList;
	}

	
	private List<PageData> getAssistantMessageList(PageData pd) throws Exception {
		
		List<PageData> pushMessageList = 
				(List<PageData>) dao.findForList("AssistantMapper.getPushMessageList", pd);		

		if(pushMessageList.size()==0){
			return pushMessageList;
		}
		//查询本人的assistantId
		String assistantId = (String) dao.findForObject("AssistantMapper.findAssistantId", pd);
		//遍历集合，预处理数据
		for(int i=0;i<pushMessageList.size();i++){
			String idTemp = pushMessageList.get(i).get("userId").toString();
			String messageType =  pushMessageList.get(i).get("messageType").toString();				
			String pushMessageId = pushMessageList.get(i).get("pushMessageId").toString();
			//如果是本人，是否是新消息
			if(idTemp.equals(assistantId)&&"0".equals(messageType)){
				if("0".equals(pushMessageList.get(i).get("ifChanged").toString())){
					pushMessageList.get(i).put("ifChanged", false);
				}else{
					pushMessageList.get(i).put("ifChanged", true);
				}
			}else{
					//添加是否是新消息，查询阅读表，自己是否读过
					pd.put("pushMessageId", pushMessageId);
					//可能看来很多遍
					List<PageData> reader = (List<PageData>) dao.findForObject("AssistantMapper.findReader", pd);
					if(reader.size()==0){
						pushMessageList.get(i).put("ifChanged", true);
					}else{
						pushMessageList.get(i).put("ifChanged", false);
					}
			}
			//
			//无论是否是本人，添加推送消息的基本信息，姓名，头像地址，阅读人数，点赞人数，图片地址
			addInfor(messageType,pushMessageList,pushMessageId,idTemp,i,pd);
				
		}
		return pushMessageList;
			
	}

	
	private void addInfor(String messageType, List<PageData> pushMessageList,String pushMessageId,
			String idTemp, int i,PageData pd) throws Exception {
		// TODO Auto-generated method stub
		if("0".equals(messageType)){
			String name = (String) dao.findForObject("AssistantMapper.getAssitantName", idTemp);
			pushMessageList.get(i).put("name", name);
			String iamgeUrl = 
					(String) dao.findForObject("AssistantMapper.getImageUrl", idTemp);
			pushMessageList.get(i).put("imageUrl", iamgeUrl);					
		}else{
			String name = 
					(String) dao.findForObject("DoctorMapper.getDocName", idTemp);
			pushMessageList.get(i).put("name", name);
			String iamgeUrl = 
					(String) dao.findForObject("DoctorMapper.getImageUrl", idTemp);
			pushMessageList.get(i).put("imageUrl", iamgeUrl);						
		}
		
		//获取阅读人数
		String readNum = 
				(String) dao.findForObject("DoctorMapper.getReaderNum", pushMessageId);
		pushMessageList.get(i).put("readNum", readNum);	
		//获取点赞人数
		String supportNum = 
				(String) dao.findForObject("DoctorMapper.getSupportNum", pushMessageId);
		pushMessageList.get(i).put("supportNum", supportNum);
		//获取图片地址
		List<String> imageList = 
				(List<String>) dao.findForList("DoctorMapper.getImageList", pushMessageId);
		pushMessageList.get(i).put("imageList", imageList);	
		//查看自己是否点过赞
		pd.put("pushMessageId", pushMessageId);
		PageData supporter = (PageData) dao.findForObject("DoctorMapper.findSupport", pd);
		if(supporter==null||supporter.get("ps_id")==null){
			pushMessageList.get(i).put("ifSupport", false);	
		}else{
			pushMessageList.get(i).put("ifSupport", true);	
		}			
	}

	
	public List<PageData> getDoctorMessageList(PageData pd) throws Exception{
		//获得本人可查看的所有推送消息
		List<PageData> pushMessageList = 
				(List<PageData>) dao.findForList("AssistantMapper.getPushMessageList", pd);		
		if(pushMessageList.size()==0){
			return pushMessageList;
		}
		//查询本人的doctorId
		String doctorId = (String) dao.findForObject("DoctorMapper.findDoctorId", pd);
		//查询数据预处理
		for(int i = 0;i<pushMessageList.size();i++){
			String idTemp = pushMessageList.get(i).get("userId").toString();
			String messageType =  pushMessageList.get(i).get("messageType").toString();				
			String pushMessageId = pushMessageList.get(i).get("pushMessageId").toString();
			//如果是本人,
			if(idTemp.equals(doctorId)&&"1".equals(messageType)){
				if("0".equals(pushMessageList.get(i).get("ifChanged").toString())){
					pushMessageList.get(i).put("ifChanged", false);
				}else{
					pushMessageList.get(i).put("ifChanged", true);
				}
				
			}else{
					//添加是否是新消息，查询阅读表，自己是否读过
					//PageData temp = new PageData();
					pd.put("pushMessageId", pushMessageId);
					//temp.put("doctorId", doctorId);
					//可能看来很多遍
					List<PageData> reader = (List<PageData>) dao.findForObject("DoctorMapper.findReader", pd);
					if(reader.size()==0){
						pushMessageList.get(i).put("ifChanged", true);
					}else{
						pushMessageList.get(i).put("ifChanged", false);
					}
			}	
			//无论是否是本人，添加推送消息的基本信息，姓名，头像地址，阅读人数，点赞人数，图片地址
			addInfor(messageType,pushMessageList,pushMessageId,idTemp,i,pd);			
		}
		return pushMessageList;		
	}


	

	
	public PageData updateAndGetPushMessageDetail(PageData pd) throws Exception {
		// 向阅读记录表中插入数据
		dao.save("AssistantMapper.insertReader", pd);		
		//获取推送详情
		PageData pushMessageInfo = 
				(PageData) dao.findForObject("AssistantMapper.getPushMessageDetail", pd);
		String pushMessageId = pushMessageInfo.get("pushMessageId")+"";
		////如果是推送消息本人查看信息，将changed字段改为0
		String readerType = pd.getString("readerType");
		String type = pushMessageInfo.get("type")+"";
		if("2".equals(readerType)||"3".equals(readerType)){
			//说明查看者是助手或医生，有可能是该推送消息的发送者
			if("2".equals(readerType)){
				//查看者身份是医生，查找医生id
			String doctorId = 	
					(String) dao.findForObject("DoctorMapper.getDocId", pd);
			pd.put("tempId", doctorId);
			//查询
			PageData pushMess  = 
					(PageData) dao.findForObject("DoctorMapper.findPushMess", pd);
			if(pushMess!= null &&pushMess.get("pm_id") != null ){				
				dao.update("DoctorMapper.updateChanged", pd);
			}			
			}else{
				//查看者是助手，获取助手id
				String userId = pd.getString("userId");
				String assistantId = 
						(String) dao.findForObject("AssistantMapper.findAssistantId", userId);
				pd.put("tempId", assistantId);
				//查询
				PageData pushMess  = 
						(PageData) dao.findForObject("AssistantMapper.findPushMess", pd);				
				if(pushMess!= null &&pushMess.get("pm_id") != null ){				
					dao.update("DoctorMapper.updateChanged", pd);
				}	
				
			}
			
			
			
		}
		
		//添加name，readNum，supportNum，ifSupport，imageUrlList，leaveMessage
		//根据type查询名字
		if("0".equals(type)){//助手
			String replierId = pushMessageInfo.get("userId")+"";
			String name = 
					(String) dao.findForObject("AssistantMapper.getAssistantById", replierId);
			pushMessageInfo.put("name", name);
		}else{
			String idTemp = pushMessageInfo.get("userId")+"";
			String name = 
					(String) dao.findForObject("DoctorMapper.getDocName", idTemp);
			pushMessageInfo.put("name", name);			
		}
		//添加readNum，supportNum，ifSupport，imageUrlList，leaveMessage
		
		String readNum = 
				(String) dao.findForObject("DoctorMapper.getReaderNum", pushMessageId);
		String supportNum = 
				(String) dao.findForObject("DoctorMapper.getSupportNum", pushMessageId);		
		pushMessageInfo.put("readNum", readNum);
		pushMessageInfo.put("supportNum", supportNum);
		//imageUrlList，leaveMessage
		List<String> imageList = 
				(List<String>) dao.findForList("DoctorMapper.getImageList", pushMessageId);
		pushMessageInfo.put("imageList", imageList);
		//查看自己是否点赞过
		
		PageData support = 
				(PageData) dao.findForObject("AssistantMapper.getSupport", pd);
		if(support==null||support.get("ps_id")==null){
			pushMessageInfo.put("ifSupport", false);
		}else{
			pushMessageInfo.put("ifSupport", true);
		}
		//添加leaveMessage集合
		List<PageData> leaveMessageList = 
							(List<PageData>) dao.findForList("AssistantMapper.getLeaveMessageList", pd);
		PageData result = new PageData();
		result.put("pushMessage", pushMessageInfo);
		result.put("leaveMessage", leaveMessageList);
		if(leaveMessageList.size()==0){
			return result;
		}
		//遍历集合，添加信息
		for(int i=0;i<leaveMessageList.size();i++){
			String leaveMessageId = leaveMessageList.get(i).get("leaveMessageId")+"";
			//根据userId找到主平台昵称，头像url
			String userId = leaveMessageList.get(i).get("userId")+"";
			PageData userInfo = 
					(PageData) dao.findForObject("AssistantMapper.getUserInfo", userId);
			if(userInfo!=null){
				leaveMessageList.get(i).put("name", userInfo.get("name"));
				leaveMessageList.get(i).put("imageUrl", userInfo.get("imageUrl"));
			}
			//添加点赞人数supportNum，查询者是否点过赞ifSupport，以及该留言是否是本人留言ifMyMessage。用于判断该用户是否有权限删除该留言
			String leaveMessageSupportNum = 
					(String) dao.findForObject("AssistantMapper.getLeaveMessageSuporNum", leaveMessageId);
			pd.put("leaveMessageId", leaveMessageId);
			leaveMessageList.get(i).put("supportNum", leaveMessageSupportNum);
			PageData supporter = 
					(PageData) dao.findForObject("AssistantMapper.getSupporter", pd);
			if(supporter==null){
				leaveMessageList.get(i).put("ifSupport", false);
			}else{
				leaveMessageList.get(i).put("ifSupport", true);
			}
			PageData leaver = 
					(PageData) dao.findForObject("AssistantMapper.getLeaver", pd);
			if(leaver==null){
				leaveMessageList.get(i).put("ifMyMessage", false);
			}else{
				leaveMessageList.get(i).put("ifMyMessage", true);
			}
			//添加replyList集合
			List<PageData> replyList = 
					(List<PageData>) dao.findForList("AssistantMapper.getReplyList", leaveMessageId);
			//遍历回复列表，添加回复者和被回复者的名字,全部为平台id
			for(int j=0;j<replyList.size();j++){
				String tempId = replyList.get(j).get("answerUserId")+"";
				String answerName = 
						(String) dao.findForObject("AssistantMapper.getUserName", tempId);
				tempId =  replyList.get(j).get("repliedUserId")+"";
				String repliedName = 
						(String) dao.findForObject("AssistantMapper.getUserName", tempId);
				replyList.get(j).put("answerName", answerName);
				replyList.get(j).put("repliedName", repliedName);
			}
			leaveMessageList.get(i).put("replyList", replyList);			
		}		
		return result;
	}

	//为推送消息添加留言
	public void insertLeaveMessage(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		pd.put("date", new Date());
		dao.save("AssistantMapper.insertLeaveMessage", pd);
	}


	public void insertSupportPushMessage(PageData pd) throws Exception {
		// 先查询是否存在，若已经点过赞，则不做任何操作
		PageData support = 
				(PageData) dao.findForObject("AssistantMapper.getSupport", pd);
		if(support!= null){
			return;
		}
		dao.save("AssistantMapper.insertSupportPushMessage", pd);
		
	}


	public void insertSupportLeaveMessage(PageData pd) throws Exception {
		// 查看是否点过赞，如果点赞过就不做任何操作
		PageData support = 
				(PageData) dao.findForObject("AssistantMapper.getSupporter", pd);
		if(support!= null){
			return;
		}
		dao.save("AssistantMapper.insertSupportLeaveMessage", pd);
	}


	public void insertReplyLeaveMessage(PageData pd) throws Exception {
		// 直接插入回复信息
		pd.put("date", new Date());
		dao.save("AssistantMapper.insertReplyLeaveMessage", pd);	
	}


	public PageData saveOrUpdatePushMessage(HttpServletRequest request) throws Exception {
		// 保存推送消息，同时保存需要
		PageData pushMessage = ImageUpLoader.saveOrUpdatePushMessage(request,dao,this);
		return pushMessage;
	}

}









